package threadsocket.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * @author Yancy
 * @program springioctest
 * @create 2021-01-18
 */
public class AskClient {
  public static void main(String[] args) throws IOException {
    // 创建DatagramSocket,用来发送或者接收数据
    DatagramSocket ds = new DatagramSocket(9999);
    Scanner scanner = new Scanner(System.in);
    for (; ; ) {
      String info = scanner.nextLine();
      if ("bye".equals(info)) {
        break;
      }
      byte[] buf = ("张三："+info).getBytes();
      InetAddress address = InetAddress.getByName("localhost");
      int port = 8888;
      DatagramPacket datagramPacket = new DatagramPacket(buf,buf.length,address,port);
      ds.send(datagramPacket);

      // 使用DatagramPacket接收一个DatagramPacket
      byte[] buf2 = new byte[1024];
      DatagramPacket datagramPacket2 = new DatagramPacket(buf2, buf2.length);
      ds.receive(datagramPacket2);
      System.out.println(new String(buf2, 0, datagramPacket2.getLength()));
    }
  }
}
